<template>
  <div>
    <el-card class="box-card">
      <el-button type="primary" size="default" icon="Plus" @click="addTrademark"
        >添加品牌</el-button
      >
      <!-- 表单组件：用于展示已有的品牌数据 -->
      <el-table style="margin: 10px 0px" border :data="trademarkArray">
        <el-table-column
          prop="id"
          label="序号"
          width="80px"
          align="center"
          type="index"
        ></el-table-column>
        <el-table-column prop="tmName" label="品牌名称"></el-table-column>
        <el-table-column label="品牌LOGO">
          <template #default="{ row }">
            <img :src="row.logoUrl" style="width: 100px; height: 100px" />
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="品牌操作">
          <template #default="{ row, $index }">
            <el-button
              type="primary"
              size="small"
              icon="Edit"
              @click="updateTrademark(row)"
              >编辑</el-button
            >

            <el-popconfirm
              title="你确定要删除品牌数据吗？"
              width="250px"
              icon="delete"
              @confirm="removeTradeMark(row.id)"
            >
              <template #reference>
                <el-button type="danger" size="small" icon="Delete"
                  >删除</el-button
                >
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器组件 -->
      <el-pagination
        @current-change="getHasTrademark"
        @size-change="sizeChange"
        :pager-count="9"
        v-model:current-page="pageNo"
        v-model:page-size="limit"
        :page-sizes="[3, 5, 7, 9]"
        :background="true"
        layout="prev, pager, next, jumper,->,sizes,total"
        :total="total"
      />
    </el-card>
    <!-- 对话框组件 -->
    <el-dialog
      v-model="dialogFormVisible"
      :title="trademarkParams.id ? '修改品牌' : '添加品牌'"
    >
      <el-form
        style="width: 80%"
        :model="trademarkParams"
        :rules="trademarkRules"
        ref="formRef"
      >
        <el-form-item label="品牌名称" label-width="100px" prop="tmName">
          <el-input
            placeholder="请输入品牌名称"
            v-model="trademarkParams.tmName"
          ></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            action="/server/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="trademarkParams.logoUrl"
              :src="trademarkParams.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { nextTick, onMounted, reactive, ref } from "vue";
import {
  reqHasTrademark,
  reqAddOrUpdateTrademark,
  reqDeleteTrademark,
} from "@/api/product/trademark/index";
import { ElMessage } from "element-plus";
import type { UploadProps } from "element-plus";
import type {
  Records,
  TradeMark,
  TradeMarkResponseData,
} from "@/api/product/trademark/type";

//当前页面
let pageNo = ref<number>(1);
//每一页展示多少条数据
let limit = ref<number>(3);
//存储已有品牌的总量
let total = ref<number>(0);
//存储已有品牌的总量
let trademarkArray = ref<Records>([]);
//控制对话框组件的显示隐藏
let dialogFormVisible = ref<boolean>(false);
//定义收集新增品牌数据
let trademarkParams = reactive<TradeMark>({
  tmName: "",
  logoUrl: "",
});
//获取el-form表单的ref组件实例
let formRef = ref<any>();
//获取已有品牌的接口封装为一个函数
const getHasTrademark = async (pager = 1) => {
  pageNo.value = pager;
  let result: TradeMarkResponseData = await reqHasTrademark(
    pageNo.value,
    limit.value,
  );
  if (result.code === 200) {
    total.value = result.data.total;
    trademarkArray.value = result.data.records;
  }
};
const sizeChange = () => {
  getHasTrademark();
};
//点击添加品牌回调
const addTrademark = () => {
  console.log("添加品牌");
  // 清空表单校验信息
  // //第一种方法
  // formRef.value?.clearValidate('tmName')
  // formRef.value?.clearValidate('logoUrl')
  // //第二种方法
  nextTick(() => {
    formRef.value?.clearValidate("tmName");
    formRef.value?.clearValidate("logoUrl");
  });
  //清空收集数据
  trademarkParams.id = 0;
  trademarkParams.tmName = "";
  trademarkParams.logoUrl = "";
  dialogFormVisible.value = true;
};
//点击修改品牌回调
const updateTrademark = (row: TradeMark) => {
  // 清空表单校验信息
  nextTick(() => {
    formRef.value?.clearValidate("tmName");
    formRef.value?.clearValidate("logoUrl");
  });
  console.log("修改品牌", row);
  //ES6语法合并对象
  Object.assign(trademarkParams, row);
  // trademarkParams.id = row.id;
  // trademarkParams.tmName = row.tmName;
  // trademarkParams.logoUrl = row.logoUrl;
  dialogFormVisible.value = true;
};
//el-dialog对话框的取消按钮回调
const handleCancel = () => {
  dialogFormVisible.value = false;
};
//el-dialog对话框的提交按钮回调
const handleSubmit = async () => {
  //表单校验通过后再发请求

  await formRef.value?.validate();

  let result: any = await reqAddOrUpdateTrademark(trademarkParams);
  if (result.code === 200) {
    //1.关闭对话框
    dialogFormVisible.value = false;
    //2.提示用户信息
    ElMessage.success(trademarkParams.id ? "修改品牌成功" : "添加品牌成功");
    //3.重新获取品牌列表
    getHasTrademark(trademarkParams.id ? pageNo.value : 1);
  } else {
    //添加品牌失败
    //1.提示用户信息
    ElMessage.error(trademarkParams.id ? "修改品牌失败" : "添加品牌失败");
    //2.关闭对话框
    dialogFormVisible.value = false;
  }
};

//上传图片组件->上传图片之前触发的钩子函数
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (rawFile.type !== "image/jpeg") {
    ElMessage.error("Avatar picture must be JPG format!");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("Avatar picture size can not exceed 2MB!");
    return false;
  }
  return true;
};
//上传图片组件->上传图片成功触发的钩子函数
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile,
) => {
  trademarkParams.logoUrl = response.data;
  //清空表单验证信息

  formRef.value.clearValidate("logoUrl");
};
//删除按钮的回调函数
const removeTradeMark = async (id: number) => {
  let result: any = await reqDeleteTrademark(id);
  if (result.code === 200) {
    //删除成功，刷新表格数据
    ElMessage.success("删除品牌成功");
    //再次获取已有的品牌数据
    getHasTrademark(
      trademarkArray.value.length > 1 ? pageNo.value : pageNo.value - 1,
    );
  } else {
    ElMessage.error("删除品牌失败");
  }
};
//自定义检验规则
const validatorTmName = (rule: any, value: any, callback: any) => {
  //品牌名称自定义校验规则
  if (value) {
    callback();
  } else {
    callback(new Error("品牌LOGO为必需项"));
  }
};

const validatorLogoUrl = (rule: any, value: any, callback: any) => {
  //品牌LOGO校验规则
};
//对话框表单校验规则
const trademarkRules = {
  tmName: [
    {
      required: true,
      trigger: "blur",
      validator: validatorTmName,
    },
  ],
  logoUrl: [
    {
      required: true,
      validator: validatorLogoUrl,
      trigger: "blur",
    },
  ],
};
//组件挂载完毕
onMounted(() => {
  getHasTrademark();
});
</script>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
